# -*- coding: utf-8 -*-
import logging
import os
import sys
from logging.handlers import RotatingFileHandler

from apps.utils.configparser import ConfigParser

reload(sys)
sys.setdefaultencoding('utf8')


class Logger(object):
    """ 日志工具 """

    @staticmethod
    def set_log_file(log_path, app_name):
        if not os.path.exists(log_path):
            try:
                os.makedirs(log_path)
            except Exception as e:
                print("其他进程已经创建,{}".format(e))
        return "{}/{}".format(log_path, app_name)

    def __init__(self, log_path, log_name, is_mask=False, c_level=logging.INFO, f_level=logging.INFO):
        config = ConfigParser('../conf/config.ini')
        config.parse()
        max_bytes = int(config.get('logger', 'max_bytes'))
        backup_count = int(config.get('logger', 'backup_count'))
        path = Logger.set_log_file(log_path, log_name)
        self.logger = logging.getLogger(path)
        self.logger.setLevel(logging.INFO)
        fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
        ch = logging.StreamHandler()
        ch.setFormatter(fmt)
        ch.setLevel(c_level)
        frh = RotatingFileHandler(filename=path, maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8')
        frh.setFormatter(fmt)
        frh.setLevel(f_level)
        self.logger.addHandler(ch)
        self.logger.addHandler(frh)
        self.is_mask = is_mask
        self.passwd = None
        self.info("log path: {}".format(path))

    def set_passwd(self, passwd):
        self.passwd = passwd

    def info(self, message):
        if self.is_mask and self.passwd is not None:
            message = message.replace(self.passwd, "***")
        self.logger.info(message)

    def warn(self, message):
        if self.is_mask and self.passwd is not None:
            message = message.replace(self.passwd, "***")
        self.logger.warn(message)

    def error(self, message):
        if self.is_mask and self.passwd is not None:
            message = message.replace(self.passwd, "***")
        self.logger.error(message)


if __name__ == '__main__':
    config1 = ConfigParser('../../conf/config.ini')
    config1.parse()
    print("backup count:", config1.get('logger', 'backup_count'))
